﻿using Microsoft.AspNetCore.Mvc;

using System.Collections.Generic;
using System.Threading.Tasks;

using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;

using Ruitu.Edu.TrainingDemo.Models;
using Ruitu.Edu.TrainingDemo.ViewModels;

namespace Ruitu.Edu.TrainingDemo.Controllers
{
    public class DisplayManagementController : Controller, IUpdateModel
    {

        private readonly IDisplayManager<Book> _bookDisplayManager;

        public DisplayManagementController(IDisplayManager<Book> bookDisplayManager)
        {
            _bookDisplayManager = bookDisplayManager;
        }
        /// <summary>
        /// 演示 Ad-hoc shape 的创建和使用
        /// 访问路径：/Ruitu.Edu.TrainingDemo/DisplayManagement/AdHocShape
        /// </summary>
        /// <returns></returns>
        public IActionResult AdHocShape()
        {
            return View();
        }

        /// 原始访问路径：/Ruitu.Edu.TrainingDemo/DisplayManagement/DisplayBook
        /// 新的访问路径：/textbook
        [HttpGet, Route("textbook")]
        public async Task<IActionResult> DisplayBook()
        {
            // 创建五本书
            var books = await Task.FromResult(CreateDemoBooks());

            // 为每本书构建显示形状
            var bookShapes = new List<object>();
            foreach (var book in books)
            {
                var shape = await _bookDisplayManager.BuildDisplayAsync(book, this);
                bookShapes.Add(shape);
            }

            // 创建一个包含所有书籍形状的视图模型
            var viewModel = new BookListViewModel
            {
                Books = bookShapes
            };

            return View(viewModel);
        }

        /// <summary>
        /// 显示单本书的详情页面
        /// 原始访问路径：/Ruitu.Edu.TrainingDemo/DisplayManagement/BookDetail/{id}
        /// </summary>
        /// <param name="id">书籍ID</param>
        /// <returns></returns>
        [HttpGet, Route("textbook/detail/{id:int}")]
        public async Task<IActionResult> BookDetail(int id)
        {
            var books = await Task.FromResult(CreateDemoBooks());
            
            if (id < 0 || id >= books.Count)
            {
                return NotFound();
            }

            var book = books[id];
            var shape = await _bookDisplayManager.BuildDisplayAsync(book, this, "Detail0");
            
            return View(shape);
        }

        /// 原始访问路径：/Ruitu.Edu.TrainingDemo/DisplayManagement/DisplayBookDescription
        public async Task<IActionResult> DisplayBookDescription()
        {
            // 模拟异步获取书籍信息
            var book = await Task.FromResult(CreateDemoBook());
            // 使用 IUpdateModel 更新模型
            if (await TryUpdateModelAsync(book, prefix: "Book"))
            {
                // 如果更新成功，重新构建显示形状
                var shape = await _bookDisplayManager.BuildDisplayAsync(book, this, "Description");
                return View(shape);
            }
            // 如果更新失败，返回原始形状
            return View(await _bookDisplayManager.BuildDisplayAsync(book, this));
        }

        private static Book CreateDemoBook()
        {
            return new()
            {
                Title = "C# 9.0 in a Nutshell",
                CoverPhotoUrl = "/Cover.jpg",
                Author = "Joseph Albahari and Ben Albahari",
                Description = "A comprehensive guide to C# 9.0, covering the latest features and best practices."
            };
        }

        private static List<Book> CreateDemoBooks()
        {
            return new List<Book>
            {
                new Book
                {
                    Title = "C# 9.0 in a Nutshell",
                    CoverPhotoUrl = "/Cover.jpg",
                    Author = "Joseph Albahari and Ben Albahari",
                    Description = "A comprehensive guide to C# 9.0, covering the latest features and best practices."
                },
                new Book
                {
                    Title = "ASP.NET Core in Action",
                    CoverPhotoUrl = "/Cover.jpg",
                    Author = "Andrew Lock",
                    Description = "Learn to build web applications with ASP.NET Core, including MVC, Web API, and SignalR."
                },
                new Book
                {
                    Title = "Entity Framework Core in Action",
                    CoverPhotoUrl = "/Cover.jpg",
                    Author = "Jon P Smith",
                    Description = "Master Entity Framework Core with practical examples and real-world scenarios."
                },
                new Book
                {
                    Title = "Design Patterns in C#",
                    CoverPhotoUrl = "/Cover.jpg",
                    Author = "Vaskaran Sarcar",
                    Description = "Learn and implement design patterns in C# with practical examples and use cases."
                },
                new Book
                {
                    Title = "Clean Code in C#",
                    CoverPhotoUrl = "/Cover.jpg",
                    Author = "Jason Alls",
                    Description = "Write clean, maintainable, and efficient C# code following best practices and principles."
                }
            };
        }
    }
}
